package com.example.demo.system.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.demo.rocketMQ.PushConsumerExample;
import com.example.demo.system.entity.User;
import com.example.demo.system.feign.UserClient;
import com.example.demo.system.service.IUserService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangys
 * @since 2025-05-19
 */
@RestController
@RequestMapping("/system/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    IUserService iUserService;

    @RequestMapping("/getUser")
    @SentinelResource(value = "demoGetUser")
    public List<User> getUser(){
        return iUserService.getUser();
    }
    @RequestMapping("/helloDemo")
    @SentinelResource(
            value = "demoHello",
            blockHandler = "handleBlock",       // 流控处理
            fallback = "fallbackForHello",      // 熔断降级处理
            exceptionsToIgnore = {IllegalArgumentException.class} // 忽略参数异常
    )
    public String hello(@RequestParam(required = false) String username) {
        // 参数校验（触发exceptionsToIgnore）
        if(StringUtils.isBlank(username)) {
            throw new IllegalArgumentException("Username cannot be empty");
        }

        // 业务日志（建议使用SLF4J）
        log.info("Calling hello service for user: {}", username);

        return iUserService.callHello(username);
    }

    // 流控处理函数（需保持相同返回类型）
    public String handleBlock(String username, BlockException ex) {
        log.warn("Triggered flow control for user: {}", username);
        return "Request too frequent, please try again later";
    }

    // 熔断降级处理
    public String fallbackForHello(String username, Throwable t) {
        log.error("Service degraded for user: {}, reason: {}", username, t.getMessage());
        return "Service temporarily unavailable";
    }

}
